package de.moc.client;

import java.util.Iterator;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.moc.shared.*;


public class SurveyResultWidget extends Composite {
	final static int WIDGET_HEIGHT = 400;
	final static int WIDGET_WIDTH = 500;
	VerticalPanel	verticalPanel;
	HorizontalPanel horizontalPanel;
	VerticalPanel	legend;
	Label			surveyTitel;
	public SurveyResultWidget() {
		verticalPanel = new VerticalPanel();
		horizontalPanel = new HorizontalPanel();

		surveyTitel = new Label("no survey selected");
		surveyTitel.setStyleName("surveyTitle");
		legend = new VerticalPanel();
		legend.setHeight("100%");
		legend.setWidth("128pt");
		verticalPanel.add(surveyTitel);
		verticalPanel.add(horizontalPanel);
		verticalPanel.setSize(  String.valueOf(WIDGET_WIDTH) + "pt",
								String.valueOf(WIDGET_HEIGHT) + "pt");
		verticalPanel.setBorderWidth(3);
		
		horizontalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
		horizontalPanel.setSpacing(5);
		horizontalPanel.setSize(  String.valueOf(WIDGET_WIDTH - legend.getOffsetWidth()) + "pt",
								  String.valueOf(WIDGET_HEIGHT - surveyTitel.getOffsetHeight()) + "pt");
		
		initWidget(verticalPanel);	
	}

	public void showSurveyResults(Survey aSurvey) {
		horizontalPanel.clear();
		legend.clear();
		
		surveyTitel.setText(aSurvey.getName());
		long maxValue = 1;
		for(Iterator<Choice> it = aSurvey.getChoices().iterator();
			it.hasNext();) {
			Choice aChoice = it.next();
			if (maxValue < aChoice.getCount())
				maxValue = aChoice.getCount();
		}
		
		int i = 1;
		for(Iterator<Choice> it = aSurvey.getChoices().iterator();
			it.hasNext();) {
			Choice aChoice = it.next();
			ResultBar result = new ResultBar(aChoice.getCount());
			long width = (WIDGET_WIDTH - 128 - 3 * horizontalPanel.getSpacing() - 6) / aSurvey.getChoices().size() - horizontalPanel.getSpacing();
			long height = (WIDGET_HEIGHT - surveyTitel.getOffsetHeight() - 3 * horizontalPanel.getSpacing()) * aChoice.getCount() / maxValue - horizontalPanel.getSpacing();
			result.setHeight(height); 
			result.setWidth(width);
			horizontalPanel.add(result);
			Label label = new Label(String.valueOf(i++) + ". " + aChoice.getName());
			label.setStyleName("resultLegend");
			legend.add(label);
		}
		horizontalPanel.add(legend);
	}
}
